package com.liangtian.mdm.base.authentication;

import com.liangtian.mdm.base.constants.MdmConstant;
import com.liangtian.mdm.base.manager.UserManager;
import com.liangtian.mdm.base.utils.EhCacheUtils;
import com.liangtian.mdm.base.utils.HttpContextUtil;
import com.liangtian.mdm.base.utils.IPUtil;
import com.liangtian.mdm.base.utils.MdmUtil;
import com.liangtian.mdm.system.user.model.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

import static com.liangtian.mdm.base.constants.MdmConstant.TOKEN_CACHE_PREFIX;

/**
 * shiro域操作
 * @author qi
 */
@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserManager userManager;

    /**
     * 支持哪个类型的token
     * @param token token类型
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }


    /**
     * 用户认证
     *
     * @param authenticationToken 身份认证 token
     * @return AuthenticationInfo 身份认证信息
     * @throws AuthenticationException 认证相关异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 这里的 token是从 JWTFilter 的 executeLogin 方法传递过来的，已经经过了解密
        String token = (String) authenticationToken.getCredentials();
        // 从 redis里获取这个 token
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        String ip = IPUtil.getIpAddr(request);


        String encryptToken = MdmUtil.encryptToken(token);
        String encryptTokenInCache = null;
        try {
            encryptTokenInCache = (String) EhCacheUtils.getValue(MdmConstant.CACHE_NAMESPACE_TOKEN, TOKEN_CACHE_PREFIX + encryptToken+ "." + ip);
        } catch (Exception ignore) {
        }
        // 如果找不到，说明已经失效
        if (StringUtils.isBlank(encryptTokenInCache)) {
            throw new AuthenticationException("token已经过期");
        }

        String username = JWTUtil.getUsername(token);

        if (StringUtils.isBlank(username)) {
            throw new AuthenticationException("token校验不通过");
        }

        SysUser user = userManager.getUser(username);

        if (user == null) {
            throw new AuthenticationException("用户名或密码错误");
        }
        if (!JWTUtil.verify(token, username, user.getUserPassword())) {
            throw new AuthenticationException("token校验不通过");
        }
        return new SimpleAuthenticationInfo(token, token, "mdm_shiro_realm");
    }

    /**
     * 授权模块，获取用户角色和权限
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用,负责在应用程序中决定用户的访问控制的方法
     * @param principals token
     * @return AuthorizationInfo 权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //因为非正常退出，即没有显式调用 SecurityUtils.getSubject().logout()
        //(可能是关闭浏览器，或超时)，但此时缓存依旧存在(principals)，所以会自己跑到授权方法里。
        //查到权限数据，返回授权信息(要包括上边的permissions)
        if (!SecurityUtils.getSubject().isAuthenticated()) {
            doClearCache(principals);
            SecurityUtils.getSubject().logout();
            clearCached();
            return null;
        }
        String username = JWTUtil.getUsername(principals.toString());

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        // 获取用户角色集
        Set<String> roleSet = userManager.getUserRoles(username);
        simpleAuthorizationInfo.setRoles(roleSet);

        // 获取用户权限集
        Set<String> permissionSet = userManager.getUserPermissions(username);
        simpleAuthorizationInfo.setStringPermissions(permissionSet);
        return simpleAuthorizationInfo;
    }

    /**
     * @param key   关键字
     * @param value 值
     * @desc 将一些数据放到ShiroSession中, 以便于其它地方使用
     */
    private void setSession(Object key, Object value) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            if (null != session) {
                session.setAttribute(key, value);
            }
        }
    }

    /**
     * @desc 清除缓存
     */
    public void clearCached() {
        PrincipalCollection principal = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principal);
    }
}
